<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .box {
            width: 200px;
            height: 200px;
            background-color: #6ff;
            position: absolute;
            left: 100px;
            top: 100px;
        }
    </style>
</head>

<body>
    <div class="box"></div>
</body>
<script>
    //  拖拽盒子在文档中移动
    // 1. 按下box  -> 选中box  -> 记录按下的位置
    // 2. 鼠标跟随 -> 盒子跟随鼠标(相对于按下的位置移动)在文档中移动
    // 3. 鼠标松开 -> 盒子不再跟随鼠标移动


    // 拖拽三剑客: onmousedown  onmousemove  onmouseup


    var box = document.getElementsByClassName("box")[0];

    // box按下时  记录按下的位置 
    box.onmousedown = function (e) {
        var e = e || window.event;

        var posX = e.offsetX;
        var posY = e.offsetY;
        console.log(posX, posY);


        // 按下时绑定移动事件
        document.onmousemove = function () {
            var e = e || window.event;

            var x = e.pageX - posX;
            var y = e.pageY - posY;


            box.style.left = x + "px";
            box.style.top = y + "px";
        }

        // 按下时绑定抬起事件
        document.onmouseup = function () {
            document.onmousemove = null;  // 鼠标松开时 清除移动事件
        }

    }









</script>

</html>